using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Text;
using System.Web;
using MvcContrib.UI.Tags;

namespace MvcContrib.UI
{
  public static class LinkExtensions
  {
    /// <summary>
    /// Creates an anchor from the current URL replacing/adding a parameter with its value
    /// </summary>
    /// <param name="text">The text.</param>
    /// <param name="paramName">Name of the param.</param>
    /// <param name="paramValue">The param value.</param>
    /// <returns></returns>
    public static Link LinkFromCurrentContext ( object text, string paramName, object paramValue )
    {
      string url = UpdateCurrentUrl(paramName, paramValue);
      return new Link(url) { InnerText = text != null ? text.ToString() : string.Empty };
    }

    /// <summary>
    /// Actions the link from current context.
    /// </summary>
    /// <param name="text">The text.</param>
    /// <param name="paramName">Name of the param.</param>
    /// <param name="paramValue">The param value.</param>
    /// <returns></returns>
    public static string ActionLinkFromCurrentContext ( object text, string paramName, object paramValue )
    {
      return LinkFromCurrentContext(text, paramName, paramValue).ToString();
    }

    /// <summary>
    /// Updates the current URL.
    /// </summary>
    /// <param name="text">The text.</param>
    /// <param name="paramName">Name of the param.</param>
    /// <param name="paramValue">The param value.</param>
    /// <returns></returns>
    public static string UpdateCurrentUrl ( string paramName, object paramValue )
    {
      string queryString = CreateQueryString(HttpContext.Current.Request.QueryString, paramName);
      string filePath = HttpContext.Current.Request.FilePath;
      return string.Format("{0}?{1}={2}{3}", filePath, paramName, paramValue, queryString);
    }

    public static string UpdateCurrentUrl ( IDictionary<string, object> querystringKeyValue, IList<string> keysToIgnore )
    {
      string[] ignoredQueryStringKeys = keysToIgnore.Union(querystringKeyValue.Keys.ToArray()).ToArray();
      string queryString = CreateQueryString(HttpContext.Current.Request.QueryString, ignoredQueryStringKeys);
      string filePath = HttpContext.Current.Request.FilePath;


      string querystringToAdd = "";
      foreach (KeyValuePair<string, object> keyValue in querystringKeyValue)
      {
        querystringToAdd += keyValue.Key + "=" + keyValue.Value + "&";
      }
      querystringToAdd = querystringToAdd.TrimEnd('&');

      return string.Format("{0}?{1}{2}", filePath, querystringToAdd, queryString);
    }

    private static string CreateQueryString ( NameValueCollection values, params string[] paramToExclude )
    {
      var builder = new StringBuilder();

      foreach (string key in values.Keys)
      {
        if (paramToExclude.Any(x => x == key)) //Don't re-add any existing 'page' variable to the querystring - this will be handled in CreatePageLink.
        {
          continue;
        }

        foreach (var value in values.GetValues(key))
        {
          builder.AppendFormat("&{0}={1}", key, HttpUtility.UrlEncode(value));
        }
      }

      return builder.ToString();
    }
  }
}